package utils;

import org.apache.log4j.Logger;
import play.mvc.Http;
import play.mvc.Scope;

/**
 * Created by FireFire on 4/6 0006.
 * 审计日志记录器
 * 配置信息在conf/log4j.properties
 * log4j.auditLogger = INFO,RollingFile
 * log4j.appender.RollingFile=org.apache.log4j.DailyRollingFileAppender
 * log4j.appender.RollingFile.File=${application.path}/logs/audit.log
 * log4j.appender.RollingFile.layout=org.apache.log4j.PatternLayout
 * log4j.appender.RollingFile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss}: %m%n
 */
public class AuditLogger {

    private static Logger log4j;

    static {
        log4j = Logger.getLogger("auditLogger");
    }
    private static void info(String message,Object... args){
        log4j.info(format(message, args));
    }

    public static void login(String message,Object... args ){
        String prefix = "[login]:";
        info(prefix+message,args);
    }

    public static void audit(String msg,Object... args){
        info("[audit]"+msg,args);
    }
    public static void auditGeneral(Long id,String message){
        String prefix = "[audit-general]:";
        String userName = Scope.Session.current()==null?"NONE":Scope.Session.current().get("username");
        String ip = Http.Request.current().remoteAddress;
        info(prefix+"%s-%s-%s-%s",id,userName,ip,message);
    }
    public static void auditDetail(Long id,String field,String oldValue,String newValue){
        String prefix = "[audit-detail]:";
        info(prefix+"%s-[%s(%s-%s)]",id,field,oldValue,newValue);
    }

    static String format(String msg, Object... args) {
        try {
            if (args != null && args.length > 0) {
                return String.format(msg, args);
            }
            return msg;
        } catch (Exception e) {
            return msg;
        }
    }
}
